/**
* 简单的摄像头测试程序
* 用于诊断摄像头问题
*/

#include <iostream>
#include <opencv2/opencv.hpp>

int main(int argc, char **argv)
{
    int camera_id = 0;
    if(argc > 1)
    {
        camera_id = atoi(argv[1]);
    }
    
    std::cout << "Testing camera " << camera_id << "..." << std::endl;
    
    // 尝试不同的后端
    std::vector<int> backends = {cv::CAP_ANY, cv::CAP_V4L2, cv::CAP_GSTREAMER};
    std::vector<std::string> backend_names = {"ANY", "V4L2", "GSTREAMER"};
    
    for(size_t i = 0; i < backends.size(); i++)
    {
        std::cout << "\nTrying backend: " << backend_names[i] << std::endl;
        
        cv::VideoCapture cap(camera_id, backends[i]);
        if(!cap.isOpened())
        {
            std::cout << "Failed to open camera with " << backend_names[i] << std::endl;
            continue;
        }
        
        std::cout << "Camera opened successfully with " << backend_names[i] << std::endl;
        
        // 设置属性
        cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);
        cap.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
        cap.set(cv::CAP_PROP_FPS, 30);
        
        // 获取实际属性
        double width = cap.get(cv::CAP_PROP_FRAME_WIDTH);
        double height = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
        double fps = cap.get(cv::CAP_PROP_FPS);
        
        std::cout << "Actual properties: " << width << "x" << height << " @ " << fps << " FPS" << std::endl;
        
        // 测试读取帧
        cv::Mat frame;
        for(int j = 0; j < 5; j++)
        {
            cap >> frame;
            if(frame.empty())
            {
                std::cout << "Failed to read frame " << j << std::endl;
                break;
            }
            else
            {
                std::cout << "Successfully read frame " << j << " - size: " << frame.cols << "x" << frame.rows 
                         << ", channels: " << frame.channels() << ", type: " << frame.type() << std::endl;
                
                // 测试颜色转换
                cv::Mat gray;
                try
                {
                    cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);
                    std::cout << "Color conversion successful" << std::endl;
                }
                catch(const cv::Exception& e)
                {
                    std::cout << "Color conversion failed: " << e.what() << std::endl;
                }
            }
        }
        
        cap.release();
        std::cout << "Test completed for " << backend_names[i] << std::endl;
    }
    
    return 0;
}
